/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 9/11/2010, 07:44:47 AM
 */

package metasymbolic;

import java.awt.Frame;
import java.io.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Mario
 */
public class NewJFrame extends javax.swing.JFrame {

    int flagText;
    
    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        jFileChooser2.setVisible(false);
        jFileChooser3.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jFileChooser2 = new javax.swing.JFileChooser();
        jFileChooser3 = new javax.swing.JFileChooser();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jTextField3 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();

        jFileChooser2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser2ActionPerformed(evt);
            }
        });

        jFileChooser3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser3ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compresión Metasimbolica");

        jButton3.setText("Examinar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setText("Diccionario:");

        jButton5.setText("Examinar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel1.setText("Archivo:");

        jButton1.setText("Comprimir");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jButton2.setText("Descomprimir");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Archivo:");

        jButton4.setText("Examinar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(441, 441, 441)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton3)
                                    .addComponent(jButton5))))
                        .addGap(1, 1, 1))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton4)))
                .addGap(40, 40, 40))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5))
                .addGap(20, 20, 20)
                .addComponent(jButton1)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        flagText=0;
        jFileChooser2.setVisible(true);
        jFileChooser2.showOpenDialog(this);
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * jButton1MouseClicked. Realiza la compresión del archivo
     * @param evt
     */
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        
        BinaryParser bParser = new BinaryParser();
        if(jTextField2.getText().equals("")||jTextField4.getText().equals(""))
       {
           Frame frame = new Frame();
           if(jTextField2.getText().equals("")){
                JOptionPane.showMessageDialog(frame,"Escriba un archivo de entrada!!!");
           }
           if(jTextField4.getText().equals("")){
               JOptionPane.showMessageDialog(frame,"Escriba el archivo que contiene el diccionario de metasimbolos!!!");
           }
       }
       else{
            int numMS = 0;
            String filler = "";
             String Header1 = "0111";
            String Header2;
            String Header3;
            String Header4;
            String[] MSS = new String[16];
            String[] MSSim = new String[16];
            String[] MSG = new String[16];
            String[] IMS;
            String offsets="";
            String MSIn="";
            try{
                File dic = new File(jTextField4.getText());
                File file = new File(jTextField2.getText());
                FileInputStream fstream = new FileInputStream(dic);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader entrada = new BufferedReader( new InputStreamReader(in) );
                InputStream is = new FileInputStream(file);
                long length = file.length();
                int i;
                String strAux;
                String[] lines = new String[500];
                byte[] bytes = new byte[(int)length];
                try {
                    strAux = entrada.readLine();
                    i=0;
                   while (strAux != null)   {
                         lines[i]= strAux;
                         strAux = entrada.readLine();
                         i++;
                    }
                    is.read(bytes);
                    //
                    int j;
                    int z;
                    int maxGap=0;
                    for(j=0;j<i-1;j++){
                        System.out.println(lines[j]);
                        if(lines[j].charAt(0)== 'M'){
                            if(lines[j+1].charAt(0)=='S'){
                                MSS[numMS] = lines[j].substring(4);
                                offsets = offsets + Integer.parseInt(lines[j].substring(5,8)) + "//";
                                numMS= numMS+1;
                                MSIn= MSIn + numMS+"//";
                            }else{
                                filler = filler + lines[j].substring(4);
                            }
                        }
                        if(lines[j].charAt(0)=='S'){
                            if(lines[j].substring(5,8).charAt(0) != ' '){
                                offsets = offsets + Integer.parseInt(lines[j].substring(5,8)) + "//";
                                MSIn= MSIn + numMS+"//";
                            }else{
                                if(lines[j].substring(5,8).charAt(1) != ' '){
                                    offsets = offsets + Integer.parseInt(lines[j].substring((5)+1,8)) + "//";
                                    MSIn= MSIn + numMS+"//";
                                }
                                else{
                                     offsets = offsets + Integer.parseInt(lines[j].substring((5)+2,8)) + "//";
                                     MSIn= MSIn + numMS+"//";
                                }
                            }
                        }
                    }
                    int aux;
                    int aux2;
                    String aux3;
                    strAux = "";
                    System.out.println(MSS[0].length());
                    String[] offsetsS= offsets.split("//");
                    String[] MSIndex= MSIn.split("//");
                    int[] offsetsI = new int[offsetsS.length];
                    for(j=0;j< offsetsS.length;j++){
                        offsetsI[j]= Integer.parseInt(offsetsS[j]);
                    }
                    for ( int pasada = 1; pasada < offsetsI.length; pasada++ ) {
                        for ( int elemento = 0;elemento < offsetsI.length - 1; elemento++ ) {
                            if ( offsetsI[ elemento ] > offsetsI[ elemento + 1 ] ){
                                aux2 = offsetsI[ elemento ];
                                aux3 = MSIndex[elemento];
                                offsetsI[ elemento ] = offsetsI[ elemento + 1 ];
                                MSIndex[ elemento ] = MSIndex[ elemento + 1 ];
                                offsetsI[ elemento + 1 ] = aux2;
                                MSIndex[ elemento + 1 ] = aux3;
                            }
                        }
                    }
                    offsets = ""+(offsetsI[0]-1)+"//";
                    int maxOffset = offsetsI[1]-offsetsI[0];
                    for(j=0;j<offsetsI.length-1;j++){
                        aux2 = offsetsI[j+1]-offsetsI[j]-1;
                        offsets = offsets + aux2 +"//";
                        if(aux2 > maxOffset){
                            maxOffset = aux2;
                        }
                        //offsets = offsets + offsetsI[j]+ "//";
                    }
                    int gapAux;
                    String gapAux1;
                    for(j=0;j<numMS;j++){
                        aux2=0;
                        MSSim[j]="";
                        MSG[j]="";
                        for(z=0;z<16;z++){
                            if(MSS[j].substring(1+z*4,4+z*4).charAt(0) != ' '){
                                aux= Integer.parseInt(MSS[j].substring(1+z*4,4+z*4));
                            }else{
                                if(MSS[j].substring(1+z*4,4+z*4).charAt(1) != ' '){
                                    aux= Integer.parseInt(MSS[j].substring((1+z*4)+1,4+z*4));
                                }
                                else{
                                    aux= Integer.parseInt(MSS[j].substring((1+z*4)+2,4+z*4));
                                }
                            }
                            if(aux!=0){
                                strAux= strAux + aux + "//";
                                MSSim[j]=MSSim[j]+ bytes[aux-1] + "//";
                                if(aux2!=0){
                                    gapAux=(aux-aux2);
                                    gapAux1= Integer.toBinaryString(gapAux);
                                    MSG[j]=MSG[j]+gapAux1+"//";
                                    if(aux-aux2 > maxGap){
                                        maxGap=aux-aux2;
                                    }
                                }
                                aux2=aux;
                            }                            
                        }
                        MSS[j]=strAux;
                        strAux = "";
                        System.out.println("Metasimbolo structure "+ j+ " ="+ MSS[j]);
                        System.out.println("Metasimbolo simbols "+ j+ " ="+ MSSim[j]);
                        System.out.println("Metasimbolo gaps "+j+" ="+ MSG[j]);

                    }
                    String gap1;

                    double nBitsXMS = (Math.log(numMS+1) / Math.log(2));
                    int nBMS= ((int) Math.rint((nBitsXMS+.5)*1)/1)-1;
                    String nBMSs= Integer.toBinaryString(nBMS);
                    while(nBMSs.length()<4){
                        nBMSs="0"+nBMSs;
                    }
                    Header2=nBMSs;
                    double bitsXO = (Math.log(maxOffset) / Math.log(2));
                    int nBO= ((int) Math.rint((bitsXO+.5)*1)/1)-1;
                    System.out.println(nBO);
                    String nBOs= Integer.toBinaryString(nBO-1);
                    while(nBOs.length()<4){
                        nBOs="0"+nBOs;
                    }
                    Header3=nBOs;
                    double bitsXG = (Math.log(maxGap+1) / Math.log(2));
                    int nBG= ((int) Math.rint((bitsXG+.5)*1)/1)-1;
                    String nBGs= Integer.toBinaryString(nBG);
                    while(nBGs.length()<4){
                        nBGs="0"+nBGs;
                    }
                    Header4=nBGs;
                    int auxInt;
                    String index="";
                    String indexTmp;
                    for(j=0;j<MSIndex.length;j++){
                        auxInt = Integer.parseInt(MSIndex[j]);
                        indexTmp= Integer.toBinaryString(auxInt);
                        while(indexTmp.length()<= nBMS){
                            indexTmp = "0"+indexTmp;
                        }
                        index= index+indexTmp;
                        //System.out.println(indexTmp);
                    }
                    String EOB="";
                    for(j=0;j<=nBMS;j++){
                        EOB=EOB+"0";
                    }
                    index= index+EOB;
                    String[] offsetP= offsets.split("//");
                    String offP="";
                    for(j=0;j<offsetP.length;j++){
                        auxInt = Integer.parseInt(offsetP[j]);
                        if(auxInt>((int)Math.pow(2,nBO))-2){
                            indexTmp=Integer.toBinaryString(auxInt-(((int)Math.pow(2,nBO))-1));
                            while(indexTmp.length()<nBO){
                                indexTmp="0"+indexTmp;
                            }
                            for(int t=0;t<nBO;t++){
                                indexTmp="1"+indexTmp;
                            }
                        }else{
                            indexTmp= Integer.toBinaryString(auxInt);
                            while(indexTmp.length()< nBO){
                                indexTmp = "0"+indexTmp;
                            }
                        }
                        offP= offP+indexTmp;
                    }
                    for(j=0;j<numMS;j++){
                        String[] gaps = MSG[j].split("//");
                        MSG[j]="";
                        for(int y = 0;y<gaps.length;y++){
                            gap1 = gaps[y];
                            while(gap1.length()<=nBG){
                                gap1="0"+gap1;
                            }
                            MSG[j]=MSG[j]+gap1;
                        }
                    }
                    gap1="";
                    EOB="";
                    for(j=0;j<=nBG;j++){
                        EOB=EOB+"0";
                    }
                    for(j=0;j<numMS;j++){
                        gap1=gap1+MSG[j]+EOB;
                    }
                    String ms1;
                    for(j=0;j<numMS;j++){
                        String[] simbols = MSSim[j].split("//");
                        MSSim[j]="";
                        for(int y = 0;y<simbols.length;y++){
                            ms1 = simbols[y];
                            ms1 = Integer.toBinaryString(Integer.parseInt(ms1)& 0xFF);
                            while(ms1.length()<8){
                                ms1="0"+ms1;
                            }
                            MSSim[j]=MSSim[j]+ms1;
                        }
                    }
                    String ms="";
                    for(j=0;j<numMS;j++){
                        ms=ms+MSSim[j];
                    }
                    String fill="";
                    String aux4;
                    String[] f = filler.split(" ");
                    byte auxB;
                    for(j=0;j<f.length;j++){
                            /*if(filler.substring((j*4)+1,4+(j*4)).charAt(0) != ' '){
                                aux= Integer.parseInt(filler.substring((j*4)+1,4+(j*4)));
                            }else{
                                if(MSS[j].substring(1+(j*4),4+(j*4)).charAt(1) != ' '){
                                    aux= Integer.parseInt(MSS[j].substring((j*4)+2,4+(j*4)));
                                }
                                else{
                                    aux= Integer.parseInt(MSS[j].substring((j*4)+3,4+(j*4)));
                                }
                            }*/
                        if(f[j].compareTo("")!= 0){
                            /*aux=Integer.parseInt(f[j]);
                            auxB= bytes[aux-1];
                            aux4=Integer.toBinaryString(auxB);
                            while(aux4.length()<8){
                                aux4="0"+aux4;
                            }
                            if(aux4.compareTo("00000000")!=0){
                                fill=fill+aux4;
                            }*/
                            if(f[j].compareTo("0")!=0){
                                aux=Integer.parseInt(f[j]);
                                auxB= bytes[aux-1];
                                aux4=Integer.toBinaryString(auxB & 0xFF);
                                while(aux4.length()<8){
                                    aux4="0"+aux4;
                                }
                                fill=fill+aux4;
                            }
                        }
                    }
                    String fileC;
                    fileC= Header1+Header2+Header3+Header4+index+offP+gap1+ms+fill;
                    //
                    System.out.println(Header1+ Header2+ Header3+Header4);
                    System.out.println("MaxOffset = "+ offsets);
                    System.out.println("Offsets = "+ offP);
                    System.out.println("Indexes = "+index);
                    System.out.println("Número de metasimbolos = "+ numMS);
                    System.out.println("Número de bytes en archivo a comp = " + bytes.length );
                    System.out.println("Filler =" + filler);
                    System.out.println("Número de bits por MS = "+ nBMSs);
                    System.out.println("gaps = "+ gap1);
                    System.out.println("ms = "+ ms);
                    System.out.println("Archivo C = "+fileC);
                    System.out.println("Tamaño de archivo en bytes="+fileC.length()/8.0);
                    while ( (fileC.length() % 8) != 0){
                        fileC = fileC +"0";
                    }
                    System.out.println("Tamaño fileC = "+ fileC.length());
                    byte salida[] = bParser.binaryStringToCharArray(fileC);

                    String arch_salida = "";
                    String arch_aux[];
                    arch_salida = (jTextField2.getText().split("\\."))[0] + ".MTS";
                    FileOutputStream fos = new FileOutputStream(arch_salida);
                    System.out.println("Tamaño: " + salida.length);
                    fos.write(salida);
                    fos.close();
                    System.out.println("Compresión realizada con éxito");
                    Frame frame = new Frame();
                    JOptionPane.showMessageDialog(frame,"Compresión realizada con éxito");
                    
                } catch (IOException ex) {
                     Frame frame = new Frame();
                    JOptionPane.showMessageDialog(frame,"Error al leer el archivo.");
                }
            }catch(FileNotFoundException ex) {
                Frame frame = new Frame();
                JOptionPane.showMessageDialog(frame,"Archivo no encontrado.");
            }
            //

            //
       }
    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        flagText = 1;
        jFileChooser2.setVisible(true);
        jFileChooser2.showOpenDialog(this);
        
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jFileChooser3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser3ActionPerformed
        // TODO add your handling code here:
        if(jFileChooser3.getSelectedFile()!= null){

            jTextField3.setText(jFileChooser3.getSelectedFile().getPath());

        }
}//GEN-LAST:event_jFileChooser3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        jFileChooser3.setVisible(true);
        jFileChooser3.showOpenDialog(this);
}//GEN-LAST:event_jButton4ActionPerformed

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        // TODO add your handling code here:
        BinaryParser bParser = new BinaryParser();
        if(jTextField3.getText().equals("")) {
            Frame frame = new Frame();
            JOptionPane.showMessageDialog(frame,"Escriba un archivo a descomprimir!!!");
        }else{
            File file = new File(jTextField3.getText());
            try{
                InputStream is = new FileInputStream(file);
                long length = file.length();
                int i;
                String strAux;
                String[] lines = new String[500];
                byte[] bytes = new byte[(int)length];
                is.read(bytes);
                String fileC="";
                for(i =0;i<bytes.length;i++){
                    strAux=(Integer.toBinaryString(bytes[i]&0XFF));
                    while(strAux.length()<8){
                        strAux = "0"+strAux;
                    }
                    fileC=fileC+strAux;
                }

                String Nibble1 = fileC.substring(0,4);
                fileC=fileC.substring(4);
                String Nibble2 = fileC.substring(0,4);
                fileC=fileC.substring(4);
                String Nibble3 = fileC.substring(0,4);
                fileC=fileC.substring(4);
                String Nibble4 = fileC.substring(0,4);
                fileC=fileC.substring(4);
                int h1=0,h2=0,h3=0,h4=0;
                for(i=0;i<4;i++){
                    if(Nibble1.charAt(i)=='1'){
                        h1=h1+(int)Math.pow(2,3-i);
                    }
                    if(Nibble2.charAt(i)=='1'){
                        h2=h2+(int)Math.pow(2,3-i);
                    }
                    if(Nibble3.charAt(i)=='1'){
                        h3=h3+(int)Math.pow(2,3-i);
                    }
                    if(Nibble4.charAt(i)=='1'){
                        h4=h4+(int)Math.pow(2,3-i);
                    }
                }
                h1=h1+1;
                h2=h2+1;
                h3=h3+1;
                h4=h4+1;
                System.out.println(fileC);
                System.out.println(h1);
                System.out.println(h2);
                System.out.println(h3);
                System.out.println(h4);
                String sU="";
                int auxSU=0;
                int cIns=0;
                int numMS=0;
                String flag="";
                while(flag.length() < h2){
                    flag = flag +"0";
                }
                int numIns=0;
                while(fileC.substring(0,h2).compareTo(flag)!=0){
                    auxSU=0;
                    for(i=0;i<h2;i++){
                        if(fileC.substring(0,h2).charAt(i)=='1'){
                            auxSU=auxSU+(int)Math.pow(2,(h2-1)-i);
                        }
                    }
                    if(auxSU>numMS){
                        numMS=auxSU;
                    }
                    numIns=numIns+1;
                    sU=sU+auxSU+"//";
                    cIns=cIns+1;
                    fileC = fileC.substring(h2);
                }
                fileC=fileC.substring(h2);
                System.out.println(sU);
                System.out.println(fileC);
                int cOff=0;
                flag="";
                int tao = 0;
                for(i=0;i<h3;i++){
                    flag=flag+"1";
                    tao = tao + (int)Math.pow(2,i);
                }
                String offsets="";
                int aux=0;
                while(cOff<cIns){
                    if(fileC.substring(0, h3).compareTo(flag)==0){
                        fileC=fileC.substring(h3);
                        aux= tao;
                    }else{
                        for(i=0;i<h3;i++){
                            if(fileC.substring(0,h3).charAt(i)=='1'){
                                aux=aux+(int)Math.pow(2,(h3-1)-i);
                            }
                        }
                        offsets=offsets+aux+"//";
                        aux=0;
                        fileC=fileC.substring(h3);
                        cOff=cOff+1;
                    }
                }
                System.out.println(flag);
                System.out.println(tao);
                System.out.println(offsets);
                System.out.println(fileC);
                flag = "";
                for(i=0;i<h4;i++){
                    flag=flag+"0";
                }
                    /*int numMS=0;
                    for(i=0;i<h2;i++){
                        numMS = numMS + (int)Math.pow(2,i);
                    }*/
                System.out.println(numMS);
                String[] MSG= new String[numMS];
                int[] numS=new int[numMS];
                int auxG;
                String gAux;
                for(i=0;i<numMS;i++){
                    gAux="0//";
                    numS[i]=1;
                    while(fileC.substring(0, h4).compareTo(flag)!=0){
                        auxG=0;
                        for(int j=0;j<h4;j++){
                            if(fileC.substring(0, h4).charAt(j)=='1'){
                                auxG = auxG+(int)Math.pow(2,(h4-1)-j);
                            }
                        }
                        numS[i]=numS[i]+1;
                        gAux=gAux+auxG+"//";
                        fileC=fileC.substring(h4);
                    }
                    fileC=fileC.substring(h4);
                    MSG[i]=gAux;
                    System.out.println(MSG[i]);
                    System.out.println(numS[i]);
                }
                System.out.println(fileC);
                int auxB;
                String simAux;
                String[] MSSim= new String[numMS];
                for(i=0;i<numMS;i++){
                    simAux="";
                    for(int j=0;j<numS[i];j++){
                        auxB=0;
                        if(fileC.substring(0, h1).charAt(0)=='1'){
                            for(int z=0;z<h1-1;z++){
                                if(fileC.substring(0,h1).charAt(1+z)=='0'){
                                    auxB = auxB+(int)Math.pow(2,(h1-2)-z);
                                }
                            }
                            fileC=fileC.substring(h1);
                            auxB= (auxB*(-1))-1;
                            simAux=simAux+auxB+"//";
                        }else{
                            for(int z=0;z<h1-1;z++){
                                if(fileC.substring(0,h1).charAt(1+z)=='1'){
                                    auxB = auxB+(int)Math.pow(2,(h1-2)-z);
                                }
                            }
                            fileC=fileC.substring(h1);
                            simAux=simAux+auxB+"//";
                        }
                    }
                    MSSim[i]=simAux;
                    System.out.println(MSSim[i]);
                }
                System.out.println(fileC);
                String filler="";
                int numSF=0;
                while(fileC.length()>=8){
                    auxB=0;
                    if(fileC.substring(0, h1).charAt(0)=='1'){
                        for(int z=0;z<h1-1;z++){
                            if(fileC.substring(0,h1).charAt(1+z)=='0'){
                                auxB = auxB+(int)Math.pow(2,(h1-2)-z);
                            }
                        }
                        fileC=fileC.substring(h1);
                        auxB= (auxB*(-1))-1;
                        filler=filler+auxB+"//";
                        numSF=numSF+1;
                    }else{
                        for(int z=0;z<h1-1;z++){
                            if(fileC.substring(0,h1).charAt(1+z)=='1'){
                                auxB = auxB+(int)Math.pow(2,(h1-2)-z);
                            }
                        }
                        fileC=fileC.substring(h1);
                        filler=filler+auxB+"//";
                        numSF=numSF+1;
                    }
                }
                String[] inst = sU.split("//");
                String[] fill=filler.split("//");
                int Usize =0;
                int ind;
                for(i=0;i<numIns;i++){
                    ind = Integer.parseInt(inst[i]);
                    Usize = Usize+numS[ind-1];
                }
                Usize = Usize+ numSF;
                System.out.println(Usize);
                System.out.println(numIns);
                String[] off = offsets.split("//");
                int[] offI= new int[numIns];
                offI[0]=Integer.parseInt(off[0])+1;
                System.out.println(offI[0]);
                for(i=1;i<numIns;i++){
                    offI[i]=offI[i-1]+Integer.parseInt(off[i])+1;
                }
                int app;
                int indB;
                byte[] bytesD =new byte[Usize];
                int[] fillInd = new int[Usize];
                for(i=0;i<Usize;i++){
                    fillInd[i]=0;
                }
                System.out.println(bytesD[0]);
                for(i=0;i<numIns;i++){
                    ind =(Integer.parseInt(inst[i]));
                    app=offI[i];
                    for(int j=0;j<numS[ind-1];j++){
                        app=app+Integer.parseInt(MSG[ind-1].split("//")[j]);
                        bytesD[app-1]=Byte.parseByte(MSSim[ind-1].split("//")[j]);
                        fillInd[app-1]=1;
                    }
                }
                int countFill=0;
                for(i=0;i<bytesD.length;i++){
                    if(fillInd[i]==0){
                        bytesD[i]=Byte.parseByte(fill[countFill]);
                        countFill=countFill+1;
                    }
                }

                try{
                    FileOutputStream fos = new FileOutputStream((jTextField3.getText().split("\\."))[0] + "_DEC.DAT");
                    fos.write(bytesD);
                    fos.close();
                    Frame frame = new Frame();
                    JOptionPane.showMessageDialog(frame,"Descompresión terminada.");
                }catch(Exception e){

                }

            } catch(Exception e){

            }
        }
    }//GEN-LAST:event_jButton2MouseClicked

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed

    private void jFileChooser2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser2ActionPerformed
        // TODO add your handling code here:
        if(jFileChooser2.getSelectedFile()!= null){
            if(flagText==0){
                jTextField2.setText(jFileChooser2.getSelectedFile().getPath());
            }else{
                jTextField4.setText(jFileChooser2.getSelectedFile().getPath());
            }

        }
        jFileChooser2.setVisible(false);
}//GEN-LAST:event_jFileChooser2ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        File file = new File(jTextField3.getText());
        MSDecoder deco = new MSDecoder(file);
        deco.decode();

    }//GEN-LAST:event_jButton2ActionPerformed


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private javax.swing.JFileChooser jFileChooser3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables

}
